import 'package:get/get.dart' hide SnackPosition;
import '../../common/index.dart';
import 'package:flutter/material.dart';

class OthersController extends GetxController
    with GetSingleTickerProviderStateMixin {
  OthersController();

  // Animation controllers
  late AnimationController giveButtonAnimationController;
  late Animation<double> giveButtonAnimation;

  // 是否初始化完成
  final is_initialized = false.obs;

  // 是否显示礼物弹窗
  final is_gift_dialog_visible = false.obs;

  // 当前选中的礼物索引
  final selected_gift_index = 0.obs;

  // 已赠送的非消耗品ID记录
  final sent_non_consumable_gifts = <String>[].obs;

  // 礼物列表 - 从公共数据文件获取
  final gift_list = gift_list_data;

  // 用户信息 - 初始化为空
  final user_data = {}.obs;

  // 从用户数据获取植物列表
  List<Map<String, dynamic>> _get_plants_list(UserModel user) {
    final plants_list = <Map<String, dynamic>>[];
    final post_service = PostService();

    // 如果用户有植物帖子，则添加到列表
    if (user.post_lists != null && user.post_lists!.isNotEmpty) {
      // 获取用户的帖子
      for (final postId in user.post_lists!) {
        // 使用异步方法获取帖子并存储结果
        post_service.get_post_by_id(postId).then((post) {
          if (post != null && post.post_image_list.isNotEmpty) {
            plants_list.add({
              'image': post.post_image_list,
              'liked': false,
              'postId': post.post_id,
            });

            // 更新UI
            if (plants_list.isNotEmpty) {
              final updatedUserData = Map<String, dynamic>.from(user_data);
              updatedUserData['plants'] = List.from(plants_list);
              user_data.value = updatedUserData;
              update(["main_view"]);
            }
          }
        });
      }
    }

    // 不再提供默认植物列表，直接返回空列表
    return plants_list;
  }

  // 检查是否已赠送过非消耗品礼物
  bool has_sent_non_consumable_gift(String giftId) {
    // 从Storage获取已赠送的非消耗品记录
    final storedGifts = Storage().get_list(
      'sent_non_consumable_gifts_${user_data['userId']}',
    );
    return storedGifts.contains(giftId);
  }

  // 保存已赠送的非消耗品记录
  void save_sent_non_consumable_gift(String giftId) {
    final userId = user_data['userId']?.toString() ?? '';
    if (userId.isNotEmpty) {
      // 从Storage获取已赠送的非消耗品记录
      final storedGifts = Storage().get_list(
        'sent_non_consumable_gifts_$userId',
      );
      // 添加新赠送的礼物ID
      if (!storedGifts.contains(giftId)) {
        storedGifts.add(giftId);
        // 保存回Storage
        Storage().set_list('sent_non_consumable_gifts_$userId', storedGifts);
      }
    }
  }

  // 发送礼物
  void send_gift() {
    final is_login = Storage().get_bool(Constants.login_status);

    if (!is_login) {
      SmartDialogHelper.show_warning('please login first before sending gift');
      return;
    }

    // 显示礼物弹窗，默认选中第一个礼物
    is_gift_dialog_visible.value = true;
    selected_gift_index.value = 0;
    update(["gift_dialog"]);
  }

  // 关闭礼物弹窗
  void close_gift_dialog() {
    is_gift_dialog_visible.value = false;
    update(["gift_dialog"]);
  }

  // 选择礼物
  void select_gift(int index) {
    if (index >= 0 && index < gift_list.length) {
      selected_gift_index.value = index;
      update(["gift_dialog"]);
    }
  }

  // 赠送礼物
  void give_gift() async {
    // 播放按钮动画
    await animateGiveButton();

    final gift = gift_list[selected_gift_index.value];
    final giftId = gift['id'] as String;

    // 如果是非消耗品，检查是否已经赠送过
    if (gift['type'] == '非消耗品') {
      // 检查是否已经赠送过这个非消耗品礼物
      if (has_sent_non_consumable_gift(giftId)) {
        SmartDialogHelper.show_warning(
          'You have already given this non-consumable gift',
        );
        return;
      }
    }

    // 这里添加礼物购买和赠送逻辑
    SmartDialogHelper.showLoading(msg: "Please wait a moment...");
    final purchaseSuccess = await PayUtils().buy_product(giftId);
    await SmartDialogHelper.dismiss();

    // 购买成功后的处理
    if (purchaseSuccess) {
      // 如果是非消耗品，记录已赠送
      if (gift['type'] == '非消耗品') {
        save_sent_non_consumable_gift(giftId);
      }

      // 显示赠送成功提示
      SmartDialogHelper.show_success("Gift sent successfully!");

      // 发送礼物消息给对方
      _send_gift_message(gift);
    }

    close_gift_dialog();
  }

  // 发送礼物消息
  void _send_gift_message(Map<String, dynamic> gift) {
    // 获取当前用户ID
    final currentUserId = UserService.to.get_now_user()?.id;
    if (currentUserId == null || user_data['userId'] == null) {
      debugPrint('发送礼物消息失败: 用户ID为空');
      return;
    }

    // 创建聊天消息
    final chatService = ChatService();
    final chatId = DateTime.now().millisecondsSinceEpoch.toString();

    final message = ChatModel(
      chat_id: chatId,
      detail: "I have sent you a gift 🎁 Hope you like it!",
      spend_user_id: currentUserId,
      receive_user_id: user_data['userId'],
      created_time: DateTime.now().toIso8601String(),
      is_reading: false,
    );

    debugPrint('message: ${message.toString()}');

    // 发送消息
    chatService.send_message(message);
  }

  // 发送消息
  void send_message() {
    final is_login = Storage().get_bool(Constants.login_status);

    if (!is_login) {
      SmartDialogHelper.show_warning(
        'please login first before sending message',
      );
      return;
    }

    debugPrint("用户数据：$user_data");
    RouteUtil.push(RouteNames.chat, extra: {'userId': user_data['userId']});
  }

  // 收藏/取消收藏植物
  void toggle_like(int index) {
    if (user_data.containsKey('plants')) {
      final plants_list = user_data['plants'] as List?;
      if (plants_list != null && index < plants_list.length) {
        final plants = List<Map<String, dynamic>>.from(plants_list);
        plants[index]['liked'] = !plants[index]['liked'];
        final updated_user_data = Map<String, dynamic>.from(user_data);
        updated_user_data['plants'] = plants;
        user_data.value = updated_user_data;
        update(["main_view"]);
      }
    }
  }

  // 点击植物跳转到详情页
  void navigate_to_plant_detail(Map<String, dynamic> plant) {
    if (plant.containsKey('postId')) {
      final postId = plant['postId'];
      // 首先获取完整的PostModel对象
      PostService().get_post_by_id(postId).then((post) {
        if (post != null) {
          RouteUtil.push(RouteNames.postDetail, extra: post);
        } else {
          SmartDialogHelper.show_error('cannot load post detail');
        }
      });
    } else {
      SmartDialogHelper.show_error('cannot view detail');
    }
  }

  // 直接设置用户数据
  void set_user_data(UserModel user) {
    user_data.value = {
      'name': user.name,
      'avatar': user.avatar_image,
      'introduction': user.signature,
      'plants': _get_plants_list(user),
      'userId': user.id,
      'is_vip': user.is_vip, // 添加 is_vip 字段
    };

    is_initialized.value = true;
    update(["others", "main_view"]);
  }

  // Animate button press
  Future<void> animateGiveButton() async {
    await giveButtonAnimationController.forward();
    await giveButtonAnimationController.reverse();
  }

  @override
  void onInit() {
    super.onInit();

    // Initialize the animation controller
    giveButtonAnimationController = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this,
    );

    // Create a scale animation
    giveButtonAnimation = Tween<double>(begin: 1.0, end: 0.9).animate(
      CurvedAnimation(
        parent: giveButtonAnimationController,
        curve: Curves.easeInOut,
      ),
    );
  }

  @override
  void onClose() {
    giveButtonAnimationController.dispose();
    super.onClose();
  }
}
